<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 导航 -->
        <el-row>
          <!-- 导航左侧 -->
          <el-col :span="12">
            <el-form :model="form">
              <el-form-item label="学科名称" label-width="80px">
                <el-input size="small" v-model="form.subjectName"></el-input>
                <el-button size="small" @click="clearFn">清除</el-button>
                <el-button
                  size="small"
                  type="primary"
                  @click="searchFn(form.subjectName)"
                  >搜索</el-button
                >
              </el-form-item>
            </el-form>
          </el-col>

          <!-- 导航右侧 -->
          <el-col :span="12">
            <el-button size="small" type="success" @click="addRoleBtn">
              <i class="el-icon-edit"></i>
              <span>新增学科</span>
            </el-button>
          </el-col>

          <!-- 新增、修改学科弹框组件 -->
          <el-dialog
            :title="isEdit ? '修改学科' : '新增学科'"
            width="25%"
            :visible.sync="showDialog"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            @close="dialogClose"
          >
            <el-form
              ref="form"
              :model="popupForm"
              :rules="rules"
              label-width="80px"
            >
              <el-form-item label="学科名称" prop="subjectName">
                <el-input
                  style="width: 100%"
                  v-model="popupForm.subjectName"
                  placeholder="请输入学科名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="是否显示" prop="isFrontDisplay">
                <el-switch
                active-color='#13ce66'
                inactive-color='red'
                  v-model="popupForm.isFrontDisplay"
                  style="width: 20%"
                ></el-switch>
              </el-form-item>
            </el-form>
            <div style="text-align: center">
              <el-button @click="call">取消</el-button>
              <el-button type="primary" @click="onSubmit" :disabled='clickShow'>确认</el-button>
            </div>
          </el-dialog>
        </el-row>

        <!-- 警告 -->
        <el-row>
          <el-alert class="alert" type="info" show-icon :closable="false"
            >数据一共 {{ counts }} 条
          </el-alert>
        </el-row>

        <!-- 表格 -->
        <el-row>
          <el-table :data="list" style="width: 100%">
            <el-table-column prop="id" type="index" label="序号" width="80">
            </el-table-column>
            <el-table-column prop="subjectName" label="学科名称" width="130">
            </el-table-column>
            <el-table-column prop="username" label="创建者"> </el-table-column>
            <el-table-column prop="addDate" label="创建日期" width="150">
              <template v-slot="scope">
                <span>{{ scope.row.addDate | formatTime }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="isFrontDisplay"
              label="前台是否显示"
              :formatter="formatter"
            >
            </el-table-column>
            <el-table-column prop="twoLevelDirectory" label="二级目录">
            </el-table-column>
            <el-table-column prop="tags" label="标签"> </el-table-column>
            <el-table-column prop="totals" label="题目数量"> </el-table-column>
            <el-table-column prop="address" label="操作" width="240">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="medium"
                  @click="
                    $router.push(
                      '/subjects/directorys?id=' +
                        scope.row.id +
                        '&name=' +
                        scope.row.subjectName
                    )
                  "
                  >学科分类</el-button
                >
                <el-button
                  type="text"
                  size="medium"
                  @click="
                    $router.push(
                      '/subjects/tags?id=' +
                        scope.row.id +
                        '&name=' +
                        scope.row.subjectName
                    )
                  "
                  >学科标签</el-button
                >
                <el-button type="text" size="medium" @click="amendFn(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  size="medium"
                  @click="delRoles(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-row>

        <!-- 分页 -->
        <el-row>
          <!-- 分页区域 -->
          <el-pagination
            background
            style="text-align: right; margin-top: 15px"
            :current-page="query.page"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="query.pagesize"
            layout="prev, pager, next, sizes, jumper"
            :total="counts"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list, detail, add, update, remove } from '../../api/hmmm/subjects'
import dayjs from 'dayjs'
export default {
  name: 'Subjects',

  // 过滤器
  filters: {
    // 格式化入职日期的方法
    formatTime (time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    }
  },

  data () {
    // 自定义规则校验
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入学科名称'))
      } else {
        if (this.popupForm.subjectName !== '') {
          this.$refs.form.validateField('checkPass')
        }
        callback()
      }
    }
    return {
      list: [], // 学科列表
      data: '', // 发送修改请求需要的对象
      showDialog: false, // 是否显示新增/修改学科弹窗
      isEdit: false, // 是否是编辑
      clickShow: false, // 只能点击一次新增弹窗的确定按钮
      // 搜索输入框
      form: {
        subjectName: '' // 学科名称
      },
      // 弹窗
      popupForm: {
        subjectName: '', // 弹窗里的学科名称
        isFrontDisplay: true // 弹窗里的是否显示
      },
      // 弹窗校验
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ]
      },
      // 分页
      query: {
        page: 1, // 页码
        pagesize: 10 // 每页条数
      },
      counts: 0, // 总数
      // 枚举 是否在页面显示
      isFrontDisplay: [
        {
          id: '',
          showId: 0,
          value: '否',
          isFrontDisplay: false
        },
        {
          id: '',
          showId: 1,
          value: '是',
          isFrontDisplay: true
        }
      ]
    }
  },
  created () {
    this.listFn()
  },
  methods: {
    // 点击删除学科
    async delRoles (data) {
      // 显示删除询问对话框
      const delRes = await this.$confirm(
        '此操作将永久删除该学科, 是否继续?',
        '提示',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }
      ).catch((err) => err)

      // 用户点击了取消，给用户进行提示
      if (delRes === 'cancel') return this.$message.info('您取消了删除')

      // 调用删除的 API
      await remove(data)

      // 判断当前数据的长度是否等于 1
      if (this.list.length === 1) {
        this.query.page--
        // 如果是第一页的最后一条
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }

      // 删除成功后的提示
      this.$message.success('删除成功')
      // 重新获取数据
      this.listFn()
    },
    // 点击新增学科
    addRoleBtn () {
      // 展示弹窗
      this.showDialog = true
      // 是否编辑状态
      this.isEdit = false
      this.clickShow = false
    },
    // 点击修改，数据回填
    async amendFn (data) {
      // console.log(data)
      // 是否编辑状态
      this.isEdit = true
      // 展示弹窗
      this.showDialog = true
      this.clickShow = false
      // 用数组的 find 方法找到 showId 的元素，再取出它的 isFrontDisplay
      const obj = this.isFrontDisplay.find(
        (item) => item.showId === data.isFrontDisplay
      )

      this.data = data
      this.popupForm.subjectName = data.subjectName
      this.popupForm.isFrontDisplay = obj.isFrontDisplay

      // console.log(this.isFrontDisplay)
    },
    // 点击确弹窗按钮
    onSubmit () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        // 判断是不是编辑
        if (!this.isEdit) {
          await add(this.popupForm)
          this.clickShow = true
          // 给用户提示
          this.$message.success('新增学科成功')
          this.query.page = 1
        } else {
          // 修改/编辑
          await update({ ...this.data, ...this.popupForm })
          // console.log(res)
          this.clickShow = true
          // 给用户提示
          this.$message.success('修改学科成功')
        }

        // 刷新列表
        this.listFn()
        // 隐藏弹窗
        this.showDialog = false
      })
    },
    // 取消/关闭弹窗按钮
    call () {
      this.showDialog = false
    },
    // 新增学科弹窗关闭的回调
    // 重置表单数据和验证规则
    dialogClose () {
      // 1. 把表单的数据项清空
      this.popupForm = {
        subjectName: '', // 弹窗里的学科名称
        isFrontDisplay: true // 弹窗里的是否显示
      }
      // 2.重置表单
      this.$refs.form.resetFields()
    },
    // 格式化 前台是否在页面显示
    formatter (row, column, cellValue, index) {
      // 用数组的 find 方法找到 showId = 1 的元素，再取出它的 value
      const obj = this.isFrontDisplay.find((item) => item.showId === cellValue)
      return obj ? obj.value : '未知'
    },

    // 获取学科列表
    async listFn () {
      const res = await list({ ...this.query, ...this.form })

      this.list = res.data.items
      this.counts = res.data.counts
      // console.log(res)
    },
    // 清除输入框
    clearFn () {
      this.form.subjectName = ''
    },
    // 筛选/搜索
    async searchFn (subjectName) {
      if (subjectName === '') {
        this.listFn()
      } else {
        // 获取全部数据
        const res = await list()
        // console.log(res)
        // 筛选出输入的名称一样的数据
        const subject = res.data.items.filter((item) => {
          return item.subjectName === subjectName
        })
        // console.log(subject)
        this.list = []
        subject.forEach(async (item) => {
          const particulars = await detail(item)
          this.list.push(particulars.data)
          // console.log(this.list)
        })
        this.query.page = 1
        this.listFn()
      }
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange (newSize) {
      this.query.pagesize = newSize
      // console.log(newSize)
      // console.log(this.query.pagesize)
      this.query.page = 1
      this.listFn()
    },

    // 当前页面发生改变时触发
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.listFn()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 0px;
}

/* 导航左侧 */
.el-input.el-input--small {
  display: inline-block;
  width: 200px;
  margin-right: 10px;
}

form.el-form {
  display: flex;
  flex-direction: column;
}

/* 导航右侧 */
button.el-button.el-button--success.el-button--small {
  float: right;
}

/* 警告 */
.el-alert.el-alert--info.is-light {
  padding-top: -5px;
  margin-bottom: 15px;
}
/* 图标 */
::v-deep i.el-alert__icon.el-icon-info.is-big {
  font-size: 16px;
  width: 15px;
}

.el-form-item--medium {
  margin-bottom: 18px;
}
</style>
